package com.lianzai.common.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

public class IpUtil {
    public static String[] IP_HEADS = new String[]{"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};

    public static String getRemoteAddress(HttpServletRequest request) {
        String[] var4 = IP_HEADS;
        int var3 = IP_HEADS.length;

        for(int var2 = 0; var2 < var3; ++var2) {
            String header = var4[var2];
            String ip = request.getHeader(header);
            if(StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                if(ip.contains(",")) {
                    ip = ip.substring(0, ip.indexOf(","));
                }

                return ip;
            }
        }

        return request.getRemoteAddr();
    }

    public static InetAddress getLocalHostAddress() {
        try {
            InetAddress e = null;
            Enumeration jdkSuppliedAddress = NetworkInterface.getNetworkInterfaces();

            while(jdkSuppliedAddress.hasMoreElements()) {
                NetworkInterface iface = (NetworkInterface)jdkSuppliedAddress.nextElement();
                Enumeration inetAddrs = iface.getInetAddresses();

                while(inetAddrs.hasMoreElements()) {
                    InetAddress inetAddr = (InetAddress)inetAddrs.nextElement();
                    if(!inetAddr.isLoopbackAddress()) {
                        if(inetAddr.isSiteLocalAddress()) {
                            return inetAddr;
                        }

                        if(e == null) {
                            e = inetAddr;
                        }
                    }
                }
            }

            if(e != null) {
                return e;
            } else {
                InetAddress jdkSuppliedAddress1 = InetAddress.getLocalHost();
                if(jdkSuppliedAddress1 == null) {
                    throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
                } else {
                    return jdkSuppliedAddress1;
                }
            }
        } catch (Exception var5) {
            throw new RuntimeException("Failed to determine LAN address: " + var5);
        }
    }
}
